export default {
	namespaced: true,
	state: () => {
		return {
			cartList: uni.getStorageSync('cart') || []
		}
	},
	getters: {
		total(state) {
			return state.cartList.filter(v => v.goods_state).reduce((sum, v) => sum += v.goods_count, 0)
		},
		totalPrice (state) {
			return state.cartList.filter(v => v.goods_state).reduce((sum, v) => sum += v.goods_count * v.goods_price, 0)
		},
		checkAll (state) {
			return state.cartList.every(v => v.goods_state)
		}
	},
	mutations: {
		addToCart(state, goods) {
			const item = state.cartList.find(v => v.goods_id === goods.goods_id)
			if (item) {
				item.goods_count++
			} else {
				state.cartList.push(goods)
			}
			uni.setStorageSync('cart', state.cartList)
		},
		setGoodsChecked(state, id) {
			const data = state.cartList.find(v => v.goods_id === id)
			if (data) {
				data.goods_state = !data.goods_state
				uni.setStorageSync('cart', state.cartList)
			}
		},
		setGoodsCount(state, payload) {
			const data = state.cartList.find(v => v.goods_id == payload.id)
			if (data) {
				data.goods_count = payload.count
				uni.setStorageSync('cart', state.cartList)
			}
		},
		delGoods(state, id) {
			state.cartList = state.cartList.filter( v => v.goods_id != id )
			uni.setStorageSync('cart', state.cartList)
		},
		setGoodsCheckedAll (state, chk) {
			state.cartList.forEach(v => v.goods_state = chk)
			uni.setStorageSync('cart', state.cartList)
		}
	}
}